/** Records events on a android input device
 * 
 * @file record.c
 * @author Kevin Lowe
 * @date December 12, 2010
 *
 * This program is compiled to run natively on android. It will run on
 * both the emulator and the Nexus One but the device should be changed
 * to event0 for the Emulator or event0,1,2,3,4,5,6 for the Nexus One.
 * 
 * Once running it will open the device and output any activity on that
 * device to the console window.
 */

/** Included Libraries */
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h> 
#include <poll.h>
#include <linux/input.h>

/** Global Variables */
struct pollfd in_fds[1]; // Array of polling file descriptors

/** Function Declarations */
void open_device();
void record();

/** The entry point of the application */
int main()
{
	open_device();
	record();	
	return 0;
}

/** Opens the device for reading events by polling. */
void open_device()
{
	int fd;
	char *buffer = "/dev/input/event6";

	// Set the file descriptor polling parameters
	in_fds[0].events = POLLIN;
	in_fds[0].fd = open(buffer, O_RDONLY | O_NDELAY);

	// Ensure the device file was opened
	if(in_fds[0].fd < 0) 
	{
		printf("Couldn't open input device %s\n", buffer);
		exit(0);
	}
	printf("Recording on %s\n", buffer);
}

/** Polls the device and records events. */
void record()
{
	// This is a standard linux structure for input events.
	struct input_event event;

	// Wait, read and record events in an infinite loop.
	while(1)
	{
		// Wait for a POLLIN event on the input device file
		if(poll(in_fds, 1, -1) < 0)
		{
			printf("Poll error\n");
			exit(0);
		}

		// Check that the event is a POLLIN event
		if(in_fds[0].revents & POLLIN)
		{
			// Read the event from the device file
			if(read(in_fds[0].fd, &event, sizeof(event)) != sizeof(event)) 
			{
				printf("Read error\n");
				exit(0);
			}
			
			// Print the event information to the console.
			printf("time %ld.%06ld, type %d, code %d, value %d\n",
				event.time.tv_sec, event.time.tv_usec, event.type, 
				event.code, event.value);
		}
	}
}




